package main

import (
	"context"
	"fmt"
	mysql "goproject/grpc/blog/blog_server/utils"
	"goproject/grpc/blog/blogpb"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

type blogItem struct {
	ID       string `bson:"_id"`
	AuthorID string `bson:"author_id"`
	Content  string `bson:"content"`
	Title    string `bson:"title"`
}

type server struct {
	blogpb.BlogServiceServer
}

func getClient() *mysql.MysqlClient {
	msconfig := mysql.MySQLConfig{
		Username: "root",
		Password: "123456",
		Host:     "8.138.135.2",
		Port:     13306,
		Database: "test",
		Charset:  "utf8mb4",
	}
	client, err := mysql.ConnectDB(msconfig)
	if err != nil {
		log.Fatalf("Failed to create MySQL client: %v", err)
	}
	return client
}

func (*server) CreateBlog(ctx context.Context, req *blogpb.CreateBlogRequest) (*blogpb.CreateBlogResponse, error) {
	fmt.Println("Create blog request")
	blog := req.GetBlog()
	/*
		data := blogItem{
			AuthorID: blog.GetAuthorId(),
			Title:    blog.GetTitle(),
			Content:  blog.GetContent(),
		}
	*/
	fmt.Println("blog from client", blog)
	client := getClient()
	client.Db.Exec("INSERT INTO blog(id, author_id,title,content) VALUES (?, ?,?,?)", blog.GetId(), blog.GetAuthorId(), blog.GetTitle(), blog.GetContent())
	return &blogpb.CreateBlogResponse{
		Blog: &blogpb.Blog{
			AuthorId: blog.GetAuthorId(),
			Title:    blog.GetTitle(),
			Content:  blog.GetContent(),
		},
	}, nil

}
func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:8801")
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}
	var opts []grpc.ServerOption
	s := grpc.NewServer(opts...)
	blogpb.RegisterBlogServiceServer(s, &server{})
	reflection.Register(s)
	s.Serve(listen)

}
